package com.xi.jetcomposedemo.activity

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material3.Card
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.xi.jetcomposedemo.R
import com.xi.jetcomposedemo.ui.compose.AppSkeleton
import com.xi.jetcomposedemo.ui.compose.Avatar
import com.xi.jetcomposedemo.ui.compose.BarrierConstraintLayoutContent
import com.xi.jetcomposedemo.ui.compose.ConstraintLayoutContent
import com.xi.jetcomposedemo.ui.compose.DecoupledConstraintLayout
import com.xi.jetcomposedemo.ui.compose.GuidelineConstraintLayout
import com.xi.jetcomposedemo.ui.theme.DeepPurpleA200
import com.xi.jetcomposedemo.ui.theme.Gray500
import com.xi.jetcomposedemo.ui.theme.Green200
import com.xi.jetcomposedemo.ui.theme.LightBlue500
import com.xi.jetcomposedemo.ui.theme.Red100

class TestComposableActivity : ComponentActivity() {
    val topics = listOf(
        "Arts $ Crafts", "Beauty", "Books", "Business", "Comics", "Culinary", "Design", "Fashion", "Film", "History", "Maths"
    )

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            AppSkeleton {
                content()
            }
        }
    }

    @Composable
    private fun content() {
        LazyColumn(modifier = Modifier.fillMaxSize()) {
            item {
                LazyRow(horizontalArrangement = Arrangement.spacedBy(9.dp)) {
                    item {
                        dateTimeEditor()
                    }
                }
            }

            item {
                LazyRow(
                    horizontalArrangement = Arrangement.spacedBy(9.dp),
                    modifier = Modifier.padding(top = 9.dp, start = 9.dp),
                ) {
                    item {
                        Avatar()
                    }

                    item {
                        PhotographerCard()
                    }
                }
            }
            item {
                Row(
                    modifier = Modifier
                        .background(color = Color.LightGray)
                        .horizontalScroll(rememberScrollState()),
                ) {
                    StaggeredGrid(rows = 3) {
                        for (topic in topics) {
                            Chip(modifier = Modifier.padding(8.dp), text = topic)
                        }
                    }
                }
            }
            // 测试约束布局
            item {
                Row(
                    modifier = Modifier
                        .background(color = Red100)
                        .padding(9.dp)
                        .horizontalScroll(rememberScrollState()),
                    horizontalArrangement = Arrangement.spacedBy(9.dp)
                ) {
                    ConstraintLayoutContent(
                        Modifier
                            // 第一个padding相当于margin
                            .padding(start = 9.dp)
                            .background(color = Color.Yellow.copy(alpha = 0.35F))
                            // 第二个padding相当于content padding
                            .padding(9.dp)
                    )

                    BarrierConstraintLayoutContent(
                        Modifier
                            .background(color = DeepPurpleA200)
                    )

                    Box(
                        modifier = Modifier
                            .background(color = Green200)
                            .width(200.dp)
                            .fillMaxHeight()
                    ) {
                        GuidelineConstraintLayout()
                    }

                    DecoupledConstraintLayout(Modifier.background(color = LightBlue500))
                }
            }
        }
    }

    /**
     * 日期输入框
     */
    @Composable
    private fun dateTimeEditor() {
        Box(
            modifier = Modifier
                .padding(top = 0.dp, bottom = 0.dp, end = 0.dp, start = 9.dp)
                .background(Color.Green, RoundedCornerShape(percent = 15))
                .wrapContentWidth()
                .wrapContentHeight(), contentAlignment = Alignment.Center
        ) {
            var text by remember { mutableStateOf("") }
            BasicTextField(value = text, onValueChange = {
                text = it
            }, textStyle = TextStyle(color = Color.White, textAlign = TextAlign.Left), cursorBrush = SolidColor(Color.Blue), decorationBox = { innerTextField ->//decorationBox内部负责编写输入框样式
                Box(
                    Modifier
                        .padding(start = 8.dp, top = 5.dp, bottom = 5.dp)
                        .width(70.dp)
                        .align(Alignment.Center)
                ) {
                    if (text.isNullOrEmpty()) {
                        Text(text = "1月24日", modifier = Modifier.fillMaxWidth(), textAlign = TextAlign.Left, color = Gray500, fontSize = 12.sp)
                    }
                    innerTextField()//自定义样式这行代码是关键，没有这一行输入文字后无法展示，光标也看不到
                }
            })
        }
    }

    @Composable
    private fun PhotographerCard(modifier: Modifier = Modifier) {
        Row(modifier = modifier
            .clip(RoundedCornerShape(4.dp))
//                .background(color = MaterialTheme.colorScheme.surface)
            .background(color = Color.White)
            .clickable { }
            .padding(16.dp)) {
            Surface(
                modifier = Modifier.size(50.dp), shape = CircleShape, color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.2F)
            ) {
                Image(
                    painter = painterResource(id = R.mipmap.meinv),
                    contentDescription = null,
                )
            }

            Column(
                modifier = Modifier
                    .padding(start = 8.dp)
                    .align(Alignment.CenterVertically)
            ) {
                Text(text = "Alfred Sisley", fontWeight = FontWeight.Bold)
                // Medium emphasis
//                CompositionLocalProvider(LocalContentColor provides MaterialTheme.colorScheme.onSurfaceVariant) {
                // Disabled emphasis
                CompositionLocalProvider(LocalContentColor provides MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f)) {
                    Text(text = "3 minutes ago", style = MaterialTheme.typography.bodySmall)
                }
            }
        }
    }

    /**
     * 列向布局，元素布局下标:
     * 0,3,6,9
     * 1,4,7,10
     * 2,5,8
     */
    @Composable
    private fun StaggeredGrid(
        modifier: Modifier = Modifier, rows: Int = 3, content: @Composable () -> Unit
    ) {
        Layout(
            modifier = modifier,
            content = content,
        ) { measurables, constraints ->
            // 一行的宽度
            val rowWidths = IntArray(rows) { 0 }
            // 一行的高度
            val rowHeights = IntArray(rows) { 0 }
            val placeables = measurables.mapIndexed { index, measurable ->
                val placeable = measurable.measure(constraints)
                val row = index % rows
                // 一行的宽度等于这一行所有元素宽度之和
                rowWidths[row] += placeable.width
                // 一行的高度等于这行中最高的那个元素的高度
                rowHeights[row] = rowHeights[row].coerceAtLeast(placeable.height)

                placeable
            }
            // 计算表格的宽高
            val tableWidth = rowWidths.maxOrNull() ?: constraints.minWidth
            val tableHeight = rowHeights.sumOf { it }
            // 计算每一行的Y坐标
            val rowY = IntArray(rows) { 0 }
            for (i in 1 until rows) {
                rowY[i] = rowY[i - 1] + rowHeights[i - 1]
            }
            layout(tableWidth, tableHeight) {
                // 每一行的X坐标
                val rowX = IntArray(rows) { 0 }
                // 设置每一个元素的坐标
                placeables.forEachIndexed { index, placeable ->
                    val row = index % rows
                    placeable.placeRelative(
                        x = rowX[row], y = rowY[row]
                    )
                    // 第一列，X坐标全部为0，下一列的X坐标要累加上前面元素的宽度
                    // 设置下一列的X坐标
                    rowX[row] += placeable.width
                }
            }
        }
    }

    @Composable
    private fun Chip(
        modifier: Modifier = Modifier, text: String
    ) {
        Card(
            modifier = modifier, border = BorderStroke(color = Color.Black, width = 0.5.dp), shape = RoundedCornerShape(8.dp)
        ) {
            Row(
                modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp), verticalAlignment = Alignment.CenterVertically
            ) {
                Box(
                    modifier = Modifier
                        .size(16.dp)
                        .background(color = MaterialTheme.colorScheme.secondary)
                )
                Spacer(modifier = Modifier.width(4.dp))
                Text(text = text)
            }
        }
    }

    @Preview(showBackground = true, showSystemUi = true)
    @Composable
    fun GreetingPreview() {
        AppSkeleton(showTitleBar = false) {
            content()
        }
    }
}